from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu


@index_blu.route("/news_list")
def news_list():
    """获取新闻首页数据并传递给前段"""
    # 1.参数获取
    cid = request.args.get('cid', '1')  # 新闻分类
    page = request.args.get('page', '1')  # 第几页
    per_page = request.args.get('per_page', '10')  # 每页显示新闻页数

    # 2.参数校验
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg='参数查询错误')

    fitters = []
    if cid != 1:
        fitters.append(News.category_id == cid)
    # 3.从数据库获取数据
    try:
        paginate = News.query.filter(*fitters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg='数据查询错误')

    # 取出当前页面的数据
    news_mode_list = paginate.items # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_li = [] #模型对象转化为字典
    for news in news_mode_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_dict_li":news_dict_li
    }

    return jsonify(erron=RET.OK, errmsg='OK',data=data)



# 2.将蓝图注册到路由
@index_blu.route('/')
def index():
    user_id = session.get('user_id')
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 根据新闻点击量排布右侧点击排行榜
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)

    # 需要将数据以字典的形式传递给前段显示 就得将news_list 对象转化为字典
    news_list_li = []
    for news in news_list:
        news_list_li.append(news.to_basic_dict())  # to_basic_dict() 是将数据转化为字典

    # 分类查询数据
    categories = Category.query.all()

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        "news_dict_li": news_list_li,
        "category_li":category_li
    }

    return render_template("news/index.html", data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
